package com.zh.juc.thread;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @Author: zhanghuan
 * @date: 2022/10/6 19:25
 * @description: create it
 */
public class FutureAPIDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        FutureTask<String> futureTask = new FutureTask<String>(() -> {
            System.out.println(Thread.currentThread().getName() + "\t---come in");
            TimeUnit.SECONDS.sleep(5);
            return "task over";
        });

        Thread t1 = new Thread(futureTask);
        t1.start();
        // 必须等结果才会离开，不管计算是否完成，容易程序堵塞
//        System.out.println(futureTask.get());


        System.out.println(Thread.currentThread().getName() + "\t ----其他任务....");

//        System.out.println(futureTask.get(3, TimeUnit.SECONDS));
        while (true) {
            if (futureTask.isDone()) {
                System.out.println(futureTask.get());
                break;
            } else {
                TimeUnit.MILLISECONDS.sleep(500);
                System.out.println("正在处理中....");
            }
        }


    }
}
